package com.jpro.framework.web.filter;

import cn.hutool.core.util.StrUtil;
import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.framework.common.util.servlet.ServletUtils;
import com.jpro.framework.security.core.util.SecurityFrameworkUtils;
import com.jpro.framework.web.core.util.WebFrameworkUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static com.jpro.framework.common.exception.enums.GlobalErrorCodeConstants.DEMO_DENY;

/**
 * 演示 Filter，禁止用户发起写操作，避免影响测试数据
 *
 * @author JPROCMS
 */
public class DemoFilter extends OncePerRequestFilter {
    //目前固定的演示用户id
    private static List<Long>demoUserIds = Arrays.asList(104L);

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String method = request.getMethod();
        return !StrUtil.equalsAnyIgnoreCase(method, "POST", "PUT", "DELETE")  // 写操作时，不进行过滤率
                || WebFrameworkUtils.getLoginUserId(request) == null; // 非登录用户时，不进行过滤
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 直接返回 DEMO_DENY 的结果。即，请求不继续
        final Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if(demoUserIds.contains(loginUserId)){
            ServletUtils.writeJSON(response, CommonResult.error(DEMO_DENY));
        }
        // 继续过滤器
        chain.doFilter(request, response);
    }

}
